package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.domain.CollarRecord;
import com.csproj.basic.service.CollarRecordService;
import com.csproj.basic.service.WarehouseService;
import com.csproj.basic.service.dto.CollarRecordDTO;
import com.csproj.basic.service.dto.WarehouseDTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing Warehouse.
 */

/**
 * 设备领用记录管理的resource
 * <p>
 * TODO action、service都秉承返回是什么资源就在那个资源的aciton、service里面写（比如查看uid=3的机构信息）
 * TODO url定义遵循/api/gateway（服务名）/v1/资源名
 * TODO 定义rap要理解资源的概念（比如图书馆的书和我借的书）
 * <p>
 * TODO action方法只负责控制调用，不处理具体业务。
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class CollarRecordResource {

    private final Logger log = LoggerFactory.getLogger(CollarRecordResource.class);

    private static final String ENTITY_NAME = "collarRecord";

    private final CollarRecordService collarRecordService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;
    public CollarRecordResource(CollarRecordService collarRecordService,UserInfoService userInfoService,SysLogsService sysLogsService) {
        this.collarRecordService = collarRecordService;
        this.sysLogsService = sysLogsService;
        this.userInfoService = userInfoService;
    }

    /**
     * POST  /collarRecord : 创建领用记录.
     *
     * @param collarRecordDTO 设备领用DTO
     * @return TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/collarRecord")
    @Timed
    public BaseDTO createCollarRecord(@Valid @RequestBody CollarRecordDTO collarRecordDTO) {
        CollarRecordDTO result = collarRecordService.saveAndGetDTO(collarRecordDTO);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_collar_record","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * PUT  /collarRecord : 修改领用记录.
     *
     * @param collarRecordDTO 领用记录DTO
     * @return
     */
    @PutMapping("/collarRecord/{id}")
    @Timed
    public BaseDTO updateCollarRecord(@Valid @RequestBody CollarRecordDTO collarRecordDTO, @PathVariable String id) throws URISyntaxException {

        CollarRecord collarRecord = collarRecordService.findOne(id);
        if(collarRecord.getReceiveDate().isAfter(collarRecordDTO.getBackDate())){
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("receivedate_is_after_backdate");
        }
        collarRecordDTO.setId(id);
        CollarRecordDTO result = collarRecordService.updateAndGetDTO(collarRecordDTO);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getAccount()+":user_update_collar_record","");

        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /collarRecord : 获取领用记录.
     *
     * @return 领用记录信息
     */
    @GetMapping("/collarRecord/all")
    @Timed
    public BaseDTO getAllCollarRecordDTOs() {
        List<CollarRecordDTO> collarRecordDTOS = collarRecordService.findAllAndGetDTO();
        return BaseDTO.createBaseDTO().setFieldList(collarRecordDTOS);
    }

    /**
     * 根据设备ID获取归还记录
     */
    @GetMapping("/collarRecord/deviceId/{deviceId}")
    @Timed
    public BaseDTO getLastCollarRecordByDeviceId(@PathVariable String deviceId){
        CollarRecordDTO collarRecordDTO = collarRecordService.findByDeviceId(deviceId);
        return BaseDTO.createBaseDTO().setData(collarRecordDTO);

    }

    /**
     * GET  /collarRecord : 获取领用记录信息.
     *
     * @return 领用记录信息
     */
    @GetMapping("/collarRecord")
    @Timed
    public BaseDTO getPageCollarRecordDTOs(@RequestParam(value = "pageNumber", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                           @RequestParam(value = "type", required = false) String type) {
        Pageable pageable = PageableTools.basicPage(pageNum, pageSize);
        Map<String, Object> map = new HashMap<>();
        BaseDTO result = collarRecordService.findPageListAndGetDTO(map, pageable);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_collar_record_list","");
        return result;
    }

    /**
     * GET  /collarRecord/:id : 根据领用记录id，获取领用记录
     *
     * @param id 领用记录id
     * @return 领用记录
     */
    @GetMapping("/collarRecord/{id}")
    @Timed
    public BaseDTO getCollarRecord(@PathVariable String id) {
        CollarRecordDTO collarRecordDTO = collarRecordService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setData(collarRecordDTO);
    }

    /**
     * DELETE  /collarRecord/:id : 根据id，删除领用记录.
     *
     * @param id id
     * @return
     */
    @DeleteMapping("/collarRecord/{id}")
    @Timed
    public BaseDTO deleteCollarRecord(@PathVariable String id) {
        collarRecordService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * 根据领用记录ids，批量删除领用记录
     *
     * @param ids ids
     * @return
     */
    @DeleteMapping("/collarRecord/deleteCollarRecords")
    @Timed
    public BaseDTO deleteIds(@RequestBody(required = false) String[] ids) {
        collarRecordService.deleteIds(ids);
        return BaseDTO.createBaseDTO().setMessage("batch_delete_success");
    }

    /**
     * 上传文件
     *
     * @param file file
     * @return
     */
    @PostMapping("/collarRecord/uploadFile")
    @Timed
    public BaseDTO uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String filePath = collarRecordService.uploadFile(request, file);
        Map<String, Object> map = new HashMap<>();
        map.put("url", filePath);
        return BaseDTO.createBaseDTO(map).setMessage("upload_file_success");
    }
}